<script lang="ts" setup>
import { IMenu, menuModel } from '@/api/system/menu';
import { FormConfig } from '@/components/Form/types';
import { useRequest } from '@/hooks/useRequest';
import { NInput } from 'naive-ui';
import { computed, ref, unref, watch } from 'vue';

interface Props {
  data: Partial<IMenu>
}

const props = defineProps<Props>();
const emits = defineEmits(['close', 'submit']);

const formData = ref<Partial<IMenu>>({
});

watch(props.data, () => {
  formData.value = props.data;
}, { immediate: true });

const config = computed<FormConfig<typeof formData.value>[]>(() => [
  {
    type: 'component',
    label: '父级菜单:',
    hidden: formData.value.parentId === -1,
    component: NInput,
    props: {
      disabled: true
    },
    key: 'parentName',
    span: 24
  },
  {
    type: 'component',
    label: '菜单名称:',
    component: NInput,
    key: 'menuName',
    span: 24,
    itemProps: {
      rule: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
      ]
    }
  },
  {
    type: 'component',
    label: '路由路径:',
    component: NInput,
    key: 'url',
    span: 24,
    itemProps: {
      rule: [
        { required: true, message: '请输入路由路径', trigger: 'blur' }
      ]
    }
  },
  {
    type: 'slot',
    slotName: 'submit',
    span: 24,
    itemProps: {
      showLabel: false
    }
  }
]);

const { run } = useRequest(menuModel.upgrade, { manual: true });
const menuUpgradeForm = ref();
async function submit() {
  await menuUpgradeForm.value.validate();
  const params = {
    ...unref(formData)
  };
  await run(params);
  emits('submit');
}

</script>
<template>
  <div>
    <Form
      ref="menuUpgradeForm"
      v-model:data="formData"
      :label-width="90"
      :config="config"
    >
    <template #submit>
        <div class="flex justify-end gap-mini">
          <NButton @click="emits('close')">
            取消
          </NButton>
          <NButton type="primary" @click="submit">
            确定
          </NButton>
        </div>
      </template>
    </Form>
  </div>
</template>
